<!-- 值日安排 -->
<template>
  <div class="duty-panly">
    <CustomTable height="965rem" ref="tableRef" type="index" v-model:form="searchForm" :tableHeader="tableHeader" api="/znjszd3/ht/jszrap/getZrRyListByZrrq" :params="reqParams" :showPagination="false">
      <template v-slot:tableTop="{ rows }">
        <el-button type="primary" class="add" plain @click="add"
          ><el-icon><Plus /></el-icon>新增</el-button
        >
      </template>
      <template v-slot:lastColumn="{ row }">
        <el-button type="primary" plain @click.stop="view(row)">
          <el-icon><View /></el-icon>
          查看</el-button
        >
        <el-button type="primary" plain @click.stop="edit(row)">
          <el-icon><Edit /></el-icon>
          修改</el-button
        >
        <el-button type="danger" plain @click.stop="del(row)">
          <el-icon><Delete /></el-icon>
          删除</el-button
        >
      </template>
    </CustomTable>
    <CustomDialog title="值日详情" v-model:dialogVisible="dialogVisible" @confirm="dialogVisible = false">
      <CustomTable v-if="DetailReqParams.jsh" height="730rem" ref="tableRef2" type="index" :tableHeader="detailHeader" api="/znjszd3/ht/jszrap/getZrjsRyApDetail" :params="DetailReqParams" :showPagination="false"> </CustomTable>
    </CustomDialog>
    <CustomDialog :title="dialogType == 'add' ? '新增监室人员值日' : '修改监室人员值日 (' + currentRoom.zdzw + ')'" v-model:dialogVisible="addDialogVisible" @confirm="saveDuty" @handleClose="handleClose">
      <div class="add-duty">
        <CustomTree
          v-if="dialogType == 'add' ? true : currentNodeKey ? true : false"
          ref="jshTreeRef"
          title="请选择监室"
          :showCheckbox="dialogType == 'add' ? false : true"
          :multiple="false"
          api="/znjszd3/comm/getJshsByDwdm"
          :params="{ type: 'tree' }"
          @leaf-node-click="onNodeClick"
          :treeProps="{ children: 'children', label: 'zdzw', disabled: dialogType == 'add' ? false : () => true }"
          v-model:currentNodeKey="currentNodeKey"
          v-model:defaultCheckedKeys="defaultCheckedKeys"
        ></CustomTree>
        <div class="box" v-loading="loading">
          <template v-if="persons.length > 0">
            <div class="toolbar">
              <div class="toolbar-left">
                <el-form :model="form" label-width="auto" style="max-width: 400rem">
                  <el-form-item label="值日日期">
                    <el-date-picker v-model="form.date" type="daterange" :disabled-date="disabledDate" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-form>
                <el-button type="primary" class="all" @click="slectAll"><i class="iconfont icon-quanxuan"></i>全选</el-button>
                <el-button type="primary" @click="cancelSelect"
                  ><el-icon><Delete /></el-icon>取消选中人员</el-button
                >
              </div>

              <div class="toolbar-right">
                <el-form :model="form" label-width="auto" inline>
                  <el-form-item label="姓名">
                    <el-input v-model="form.xm" clearable style="width: 120px" placeholder="请输入姓名" />
                  </el-form-item>
                  <el-form-item>
                    <el-radio-group v-model="form.radio">
                      <el-radio value="rssj">入所时间</el-radio>
                      <el-radio value="cwh">床位号</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
                <el-button type="primary" @click="getData"
                  ><el-icon><Search /></el-icon>查询</el-button
                >
              </div>
            </div>
            <el-scrollbar style="height: 185rem">
              <div class="persons">
                <div class="person flex-center" :draggable="item.selected" v-for="(item, index) in persons" :key="index" @click="selectPerson(item)">
                  {{ item.xm }}
                  <label v-if="item.selected" class="selected-label flex-center"
                    ><el-icon color="#fff"><Select /></el-icon
                  ></label>
                  <span class="bed-num" v-if="item.cwh">({{ item.cwh }}床)</span>
                  <!-- <i class="iconfont icon-chuang"></i> -->
                </div>
              </div>
            </el-scrollbar>

            <el-divider>
              <div class="line">
                <el-icon size="16"><star-filled /></el-icon> <span>选择人员拖动到对应区域</span> <el-icon size="16"><star-filled /></el-icon>
              </div>
            </el-divider>
            <el-scrollbar>
              <div v-if="dialogType == 'add'" class="add-duty-box">
                <div class="duty-item" v-for="dutyName in dutyItemArr" :key="dutyName.id">
                  <div class="duty-name" :data-id="dutyName.id">
                    <div class="person" v-for="person in dutyName.list" :key="person.id" @click="delSelect(dutyName, person)">
                      {{ person.xm }}
                    </div>
                  </div>
                  <div class="text flex-center">
                    {{ dutyName.zrsx }}
                  </div>
                </div>
              </div>
              <div v-else class="edit-duty-box">
                <div class="duty-item" v-for="(item, index) in dutyInfo" :key="item.date">
                  <div class="duty-date flex-center">{{ item.date }}</div>
                  <div class="duty-name-box">
                    <div class="duty-name-wrap" v-for="(dutyName, dutyIndex) in item.list" :key="dutyName.rid">
                      <div class="duty-name" :data-index="index" :data-dutyNameIndex="dutyIndex">
                        <div class="person flex-center" v-for="person in dutyName.persons" :key="person.rybh" @click="delPerson(index, dutyIndex, person)">{{ person.xm }}</div>
                      </div>
                      <div class="text flex-center">{{ dutyName.zrsx }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </template>

          <CustomEmpty v-else></CustomEmpty>
        </div>
      </div>
    </CustomDialog>
  </div>
</template>

<script setup name="personDutyPlan">
import { ref, onBeforeMount, onMounted, computed, watch, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/index'
import dayjs from 'dayjs'
const props = defineProps({})
const tableRef = ref()
const tableRef2 = ref()
const jshTreeRef = ref()
const dialogVisible = ref(false)
const addDialogVisible = ref(false)
const loading = ref(false)
const isOver = ref(false)
const dialogType = ref('add')
const pch = ref('') //当前修改值日的批次号
const defaultCheckedKeys = ref([])

const currentNodeKey = ref('')
const form = ref({
  date: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  xm: '',
  radio: 'rssj'
})
const searchForm = ref({
  jsh: '',
  zrrq: dayjs().format('YYYY-MM-DD')
})
const reqParams = ref({
  zrrq: dayjs().format('YYYY-MM-DD')
})
const DetailReqParams = ref({
  jsh: '',
  zrrq: ''
})
const currentRoom = ref({})
const persons = ref([]) //监室所有人员
const dutyItemArr = ref([]) //新增值日人员
const dutyInfo = ref([]) //修改值日信息
const tableHeader = ref([
  { key: 'jszw', label: '监室号' },
  { key: 'zrrq', label: '值日日期' }
])
const detailHeader = ref([
  { key: 'zrsx', label: '值日事项' },
  { key: 'ryxms', label: '人员姓名' },
  { key: 'bgr', label: '变更人' }
])

watch(
  persons,
  (newVal) => {
    if (newVal.length > 0) {
      nextTick(() => {
        let sources = document.getElementsByClassName('person')
        sources = Array.from(sources)
        sources.forEach((person) => {
          // person.addEventListener('drag', (event) => {
          //   console.log('dragging')
          // })
          person.ondrag = (event) => {
            console.log('dragging')
          }

          // person.addEventListener('dragstart', (event) => {
          //   // console.log(event.target)
          //   // 保存被拖动元素的引用
          //   // dragged = event.target
          //   event.dataTransfer.setData('selectedPerson', JSON.stringify(persons.value.filter((item) => item.selected)))
          //   // 设置为半透明
          //   event.target.classList.add('dragging')
          // })
          person.ondragstart = (event) => {
            // console.log(event.target)
            // 保存被拖动元素的引用
            // dragged = event.target
            event.dataTransfer.setData('selectedPerson', JSON.stringify(persons.value.filter((item) => item.selected)))
            // 设置为半透明
            event.target.classList.add('dragging')
          }
          // person.addEventListener('dragend', (event) => {
          //   // 拖动结束，重置透明度
          //   event.target.classList.remove('dragging')
          // })
          person.ondragend = (event) => {
            // 拖动结束，重置透明度
            event.target.classList.remove('dragging')
          }
        })

        let dragTargets = document.getElementsByClassName('duty-name')
        dragTargets = Array.from(dragTargets)
        // console.log(dragTargets)
        dragTargets.forEach((target) => {
          // console.log(target)
          // target.addEventListener(
          //   'dragover',
          //   (event) => {
          //     // 阻止默认行为以允许放置
          //     event.preventDefault()
          //   },
          //   true
          // );

          target.ondragover = (event) => {
            // 阻止默认行为以允许放置
            event.preventDefault()
          }
          // target.addEventListener('dragenter', (event) => {
          //   // 在可拖动元素进入潜在的放置目标时高亮显示该目标
          //   event.target.classList.add('dragover')
          //   // console.log('dragenter')
          // })
          target.ondragenter = (event) => {
            // 在可拖动元素进入潜在的放置目标时高亮显示该目标
            event.target.classList.add('dragover')
            // console.log('dragenter')
          }
          // target.addEventListener('dragleave', (event) => {
          //   // 在可拖动元素离开潜在放置目标元素时重置该目标的背景
          //   event.target.classList.remove('dragover')
          // })
          target.ondragleave = (event) => {
            // 在可拖动元素离开潜在放置目标元素时重置该目标的背景
            event.target.classList.remove('dragover')
          }
          // target.addEventListener('drop', (event) => {
          //   // console.log(event.currentTarge)
          //   console.log(event.target.dataset.zrsx)
          //   const dutyName = event.target.dataset.zrsx
          //   var data = JSON.parse(event.dataTransfer.getData('selectedPerson'))
          //   console.log('拖拽的数据:', data)
          //   const currentItem = dutyItemArr.value.find((item) => item.zrsx == dutyName)

          //   data.forEach((item) => {
          //     const result = currentItem.list.some((x) => x.rybh == item.rybh)
          //     if (!result) {
          //       currentItem.list.push(item)
          //     }
          //   })

          //   // console.log(arr)

          //   // console.log('drop')
          //   // 阻止默认行为（会作为某些元素的链接打开）

          //   event.preventDefault()
          //   // 将被拖动元素移动到选定的目标元素中

          //   event.target.classList.remove('dragover')
          //   // dragged.parentNode.removeChild(dragged)
          //   // event.target.appendChild(dragged)
          // })
          target.ondrop = (event) => {
            console.log(event.target.dataset)

            var dargingPerson = JSON.parse(event.dataTransfer.getData('selectedPerson'))
            console.log('拖拽的数据:', dargingPerson)

            //拖动人员放置到值日名称所在容器

            if (dialogType.value == 'add') {
              const id = event.target.dataset.id

              const currentItem = dutyItemArr.value.find((item) => item.id == event.target.dataset.id)

              dargingPerson.forEach((item) => {
                const result = currentItem.list.some((x) => x.rybh == item.rybh)
                if (!result) {
                  currentItem.list.push(item)
                }
              })
            } else {
              const dataset = event.target.dataset

              const persons = dutyInfo.value[dataset.index].list[dataset.dutynameindex].persons

              dargingPerson.forEach((item) => {
                const result = persons.some((x) => x.rybh == item.rybh)
                if (!result) {
                  persons.push({
                    rybh: item.rybh,
                    xm: item.xm
                  })
                  console.log(persons)
                }
              })
            }

            // console.log(arr)

            // console.log('drop')
            // 阻止默认行为（会作为某些元素的链接打开）

            event.preventDefault()
            // 将被拖动元素移动到选定的目标元素中

            event.target.classList.remove('dragover')
            // dragged.parentNode.removeChild(dragged)
            // event.target.appendChild(dragged)
          }
        })
      })
    }
  },
  {
    deep: true
  }
)
onMounted(() => {})
const getData = () => {
  loading.value = true
  http('/znjszd3/ht/jszrap/getZyryByJsh', 'get', {
    xm: form.value.xm,
    jsh: currentRoom.value.zddm,
    ryorderby: form.value.radio
  })
    .then((res) => {
      console.log(res)
      persons.value = res.data.ryList
      dutyItemArr.value = res.data.zrsxList.map((item) => {
        return {
          id: item.id,
          zrsx: item.zrsx,
          list: []
        }
      })
      console.log(dutyItemArr.value)
    })
    .finally((res) => {
      loading.value = false
    })
}

const add = () => {
  dialogType.value = 'add'

  defaultCheckedKeys.value = []
  addDialogVisible.value = true
}

const view = (row) => {
  console.log(row)
  DetailReqParams.value.jsh = row.jsh
  DetailReqParams.value.zrrq = row.zrrq
  dialogVisible.value = true
}
const edit = async (row) => {
  dialogType.value = 'edit'
  currentRoom.value.zddm = row.jsh
  currentRoom.value.zdzw = row.jszw
  currentNodeKey.value = row.jsh
  defaultCheckedKeys.value.push(row.jsh)
  addDialogVisible.value = true
  await nextTick()
  http('/znjszd3/ht/jszrap/getZrryListByPch', 'get', {
    jsh: row.jsh,
    zrrq: row.zrrq,
    ryorderby: form.value.radio
  }).then((res) => {
    dutyInfo.value = []

    persons.value = res.data.ryList
    pch.value = res.data.zrrqsx.pch

    const info = res.data.zrrqsx
    info.zrrqArray.forEach((item) => {
      const obj = {}
      dutyInfo.value.push({
        pch: info.pch,
        date: item,
        list: info[item]
      })
    })
    dutyInfo.value.forEach((item) => {
      item.list.forEach((subItem, subIndex) => {
        subItem.persons = []
        subItem.rybhs.split(',').forEach((x, i) => {
          subItem.persons.push({
            rybh: x,
            xm: subItem.ryxms.split(',')[i]
          })
        })
      })
    })
    console.log(dutyInfo.value)
    nextTick(() => {
      // console.log(jshTreeRef.value.treeRef)
      // jshTreeRef.value.treeRef.setCurrentKey(row.jsh)
    })
  })
}

const del = (row) => {
  console.log(row)
  ElMessageBox.confirm('确定要删除该条数据吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http(
        '/znjszd3/ht/jszrap/delZrRy',
        'post',
        {
          jsh: row.jsh,
          zrrq: row.zrrq
        },
        false
      ).then((res) => {
        if (res.status == 200) {
          ElMessage.success(res.message[0])
          tableRef.value.getData()
        }
      })
    })
    .catch(() => {})
}
const onNodeClick = (node) => {
  currentRoom.value = node
  loading.value = true
  getData()
}

const selectPerson = (person) => {
  console.log(person)
  person.selected = !person.selected
}
//设置今天之前的日期不可选择
const disabledDate = (time) => {
  // return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0))
  return time.getTime() < Date.now() - 8.64e7
}
const slectAll = () => {
  persons.value.forEach((item) => {
    item.selected = true
  })
}
const cancelSelect = () => {
  persons.value.forEach((item) => {
    item.selected = false
  })
}
//新增-删除某个值日人员
const delSelect = (dutyItem, person) => {
  console.log(dutyItem)
  const index = dutyItem.list.findIndex((item) => item.rybh == person.rybh)
  dutyItem.list.splice(index, 1)
}
//编辑 - 删除某个值日人员
const delPerson = (index, dutyNameIndex, person) => {
  const persons = dutyInfo.value[index].list[dutyNameIndex].persons
  // console.log(persons)
  const i = persons.findIndex((item) => item.rybh == person.rybh)
  persons.splice(i, 1)
  // console.log(dutyName)
  // console.log(person)
}
const saveDuty = () => {
  if (dialogType.value == 'add') {
    let arr = dutyItemArr.value.filter((item) => item.list.length > 0)
    if (arr.length == 0) return ElMessage.warning('请先设置值日人员')
    arr = arr.map((item) => {
      return {
        rid: item.id,
        jsh: currentRoom.value.zddm,
        rybhs: item.list.map((x) => x.rybh).join(','),
        ryxms: item.list.map((x) => x.xm).join(',')
      }
    })

    http(
      '/znjszd3/ht/jszrap/addZrRy',
      'post',
      {
        isOver: isOver.value,
        beginDate: form.value.date[0],
        endDate: form.value.date[1],
        jsh: currentRoom.value.zddm,
        list: arr
      },
      false
    ).then((res) => {
      console.log(res)
      if (res.status == 200) {
        ElMessage.success(res.message[0])
        addDialogVisible.value = false
        isOver.value = false
        tableRef.value.getData()
        persons.value = []
        dutyItemArr.value = []
      }
      if (res.status == 300) {
        ElMessageBox.confirm(res.message.join(','), '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            isOver.value = true
            saveDuty()
          })
          .catch(() => {})
      }
    })
  } else {
    let list = []
    console.log(dutyInfo.value)
    dutyInfo.value.forEach((item) => {
      item.list.forEach((subItem) => {
        if (subItem.persons.length > 0) {
          list.push({
            rybhs: subItem.persons.map((x) => x.rybh).join(','),
            ryxms: subItem.persons.map((x) => x.xm).join(','),
            jsh: currentRoom.value.zddm,
            rid: subItem.rid
          })
        }
      })
    })

    //跨日期值日合并到同一天值日,合并相同值日名称，的人员编号和人名
    if (form.value.date[0] == form.value.date[1]) {
      list = list.reduce((acc, obj) => {
        const index = acc.findIndex((o) => o.rid === obj.rid)
        if (index != -1) {
          acc[index].rybhs = Array.from(new Set((acc[index].rybhs + ',' + obj.rybhs).split(','))).join(',')
          acc[index].ryxms = Array.from(new Set((acc[index].ryxms + ',' + obj.ryxms).split(','))).join(',')
        } else {
          acc.push(obj)
        }
        return acc
      }, [])
    }
    console.log(list)

    http(
      '/znjszd3/ht/jszrap/updateZrryap',
      'post',
      {
        beginDate: form.value.date[0],
        endDate: form.value.date[1],
        jsh: currentRoom.value.zddm,
        pch: pch.value,
        list: list
      },
      false
    ).then((res) => {
      if (res.status == 200) {
        dutyInfo.value = []
        ElMessage.success(res.message[0])
        addDialogVisible.value = false
        tableRef.value.getData()
      }
    })
  }
}
const handleClose = () => {
  persons.value = []
  dutyItemArr.value = []
  form.value = {
    date: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
    xm: '',
    radio: 'rssj'
  }
}
</script>
<style lang="scss" scoped>
.add-duty {
  border: var(--el-border);

  height: 730px;
  display: flex;
  border-radius: 6px;
  .toolbar {
    padding: 0 10px;
    height: 41px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid var(--el-border-color);
    .toolbar-left,
    .toolbar-right {
      display: flex;
      // border: 1px solid red;
    }
    .el-button.all {
      margin-left: 15px;
    }
  }
  .box {
    padding: 10px;
    // flex: 1;
    width: calc(100% - 200px);
    border-left: var(--el-border);
    .el-scrollbar {
      height: 415px;
      // margin: 10px;
    }

    .persons {
      padding: 10px;
      display: grid;
      grid-template-columns: repeat(10, 1fr);
      grid-auto-rows: 50px;
      gap: 15px;
      // border: 1px solid #ccc;
      // height: 190px;
      .person {
        position: relative;
        border: 1px solid var(--el-color-primary);
        background-color: var(--el-color-primary-light-9);
        border-radius: 4px;
        cursor: pointer;
        overflow: hidden;
        user-select: none;
        font-size: 16px;

        // height: 50px;
        .selected-label {
          position: absolute;
          right: -15px;
          top: -6px;
          width: 40px;
          height: 24px;
          background: var(--el-color-primary);
          text-align: center;
          transform: rotate(45deg);
          .el-icon {
            font-size: 12px;
            margin-top: 11px;
            transform: rotate(-45deg);
          }
        }
        .bed-num {
          margin-left: 5px;
        }
        &.dragging {
          opacity: 0.5;
        }
      }
    }
    .el-divider {
      // margin: 10px;
      width: 100%;
      .line {
        display: flex;
        justify-content: center;
        align-items: center;
        > span {
          position: relative;
          top: 2px;
        }
      }
    }
    .add-duty-box {
      margin-right: 20px;
      padding: 10px;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10px;
      border-radius: 6px;

      // overflow: auto;
      .duty-item {
        // padding: 10px;
        position: relative;

        height: 130px;
        border: 1px solid #ccc;
        border-radius: 6px;

        // overflow: auto;
        .duty-name {
          padding: 10px;
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          // border: 1px solid red;
          z-index: 2;
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          grid-auto-rows: 36px;
          gap: 10px;
          overflow: auto;
          .person {
            border: 1px solid var(--el-color-primary);
            background-color: var(--el-color-primary-light-9);
            border-radius: 4px;
            // cursor: pointer;
            overflow: hidden;
            user-select: none;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          &.dragover {
            background-color: var(--el-color-primary-light-9);
            opacity: 0.7;
          }
        }

        .text {
          position: absolute;
          width: 100%;
          height: 100%;
          font-size: 30px;
          font-weight: 700;
          color: rgb(224, 221, 221, 0.8);
          letter-spacing: 10px;
          z-index: 1;
        }
      }
    }
    .edit-duty-box {
      padding: 0 5px;
      // border: 1px solid red;
      .duty-date {
        width: 100px;
        height: 30px;
        background-color: var(--el-color-primary);
        border-radius: 6px;
        color: #fff;
      }
      .duty-item {
        margin-bottom: 20px;
      }
      .duty-name-box {
        margin-right: 15px;
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
        border-radius: 6px;

        .duty-name-wrap {
          position: relative;
          height: 130px;
          border: var(--el-border);
          border-radius: 6px;
          margin-top: 5px;
          .duty-name {
            padding: 10px;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            // border: 1px solid red;
            z-index: 2;
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            grid-auto-rows: 36px;
            gap: 10px;
            overflow: auto;
            .person {
              border: 1px solid var(--el-color-primary);
              background-color: var(--el-color-primary-light-9);
              border-radius: 4px;
              // cursor: pointer;
              overflow: hidden;
              user-select: none;

              cursor: pointer;
            }
            &.dragover {
              background-color: var(--el-color-primary-light-9);
              opacity: 0.7;
            }
          }

          .text {
            position: absolute;
            width: 100%;
            height: 100%;
            font-size: 30px;
            font-weight: 700;
            color: rgb(224, 221, 221, 0.8);
            letter-spacing: 10px;
            z-index: 1;
          }
        }
      }
    }
  }
}
</style>
